/**
 * WebSocket工具类
 * 用于处理全局的WebSocket连接和消息监听
 */
class WebSocketUtil {
    constructor() {
        this.websocket = null;
        this.isConnected = false;
        this.phone = '';
        this.callbacks = {}; // 存储事件回调
    }
    
    /**
     * 初始化WebSocket连接
     */
    init(phone) {
        if (this.isConnected) {
            console.log('WebSocket已连接');
            return;
        }
        
        this.phone = phone;
        const wsuri = `ws://localhost:6008/phone-client/websocket/call/${phone}`;
        
        try {
            this.websocket = new WebSocket(wsuri);
            
            this.websocket.onopen = () => {
                console.log('WebSocket连接成功');
                this.isConnected = true;
                this.trigger('open');
            };
            
            this.websocket.onmessage = (res) => {
                console.log('收到WebSocket消息:', res.data);
                this.trigger('message', res.data);
                this.handleCallMessage(res.data);
            };
            
            this.websocket.onclose = () => {
                console.log('WebSocket连接关闭');
                this.isConnected = false;
                this.trigger('close');
                // 尝试重连
                this.reconnect();
            };
            
            this.websocket.onerror = (err) => {
                console.error('WebSocket错误:', err);
                this.isConnected = false;
                this.trigger('error', err);
                // 尝试重连
                this.reconnect();
            };
        } catch (e) {
            console.error('WebSocket初始化失败:', e);
            this.reconnect();
        }
    }
    
    /**
     * 发送消息
     */
    send(message) {
        if (!this.isConnected || !this.websocket) {
            console.error('WebSocket未连接，无法发送消息');
            return false;
        }
        
        try {
            this.websocket.send(message);
            return true;
        } catch (e) {
            console.error('发送消息失败:', e);
            return false;
        }
    }
    
    /**
     * 关闭连接
     */
    close() {
        if (this.websocket) {
            this.websocket.close();
            this.isConnected = false;
        }
    }
    
    /**
     * 重连机制
     */
    reconnect() {
        if (!this.phone) return;
        
        console.log('尝试重连WebSocket...');
        setTimeout(() => {
            this.init(this.phone);
        }, 3000);
    }
    
    /**
     * 处理通话相关消息
     */
    handleCallMessage(message) {
        try {
            const data = JSON.parse(message);
            if (data.type === 'call') {
                // 有来电，跳转到通话页面
                uni.navigateTo({
                    url: `/pages/call/call?myPhone=${this.phone}&fromPhone=${data.from}&isIncoming=true`
                });
            }
        } catch (e) {
            console.error('处理通话消息错误:', e);
        }
    }
    
    /**
     * 注册事件监听
     */
    on(event, callback) {
        if (!this.callbacks[event]) {
            this.callbacks[event] = [];
        }
        this.callbacks[event].push(callback);
    }
    
    /**
     * 触发事件
     */
    trigger(event, data) {
        if (this.callbacks[event]) {
            this.callbacks[event].forEach(callback => {
                callback(data);
            });
        }
    }
}

// 导出单例
export default new WebSocketUtil();
